import 'package:pacsun/view/create/createGuide.dart';
import 'package:pacsun/view/create/guide_dialog.dart';
import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:showcaseview/showcaseview.dart';

// -------------------------------------------------------------------------
import '../../provider/themeProv.dart' show ThemeModeProvider;

// -------------------------------------------------------------------------
import './createStatistics.dart' show CreateStatistics;

// -------------------------------------------------------------------------
import 'package:pacsun/model/userModel.dart' show UserModel;

// -------------------------------------------------------------------------
import 'package:pacsun/provider/themeProv.dart' show ThemeModeProvider;
import 'package:pacsun/provider/userProv.dart' show UserProvider;
import 'package:pacsun/constants/constant.dart';

// -------------------------------------------------------------------------
class CreateHeader extends StatelessWidget {
  final GlobalKey guideKey;

  const CreateHeader({super.key, required this.guideKey});

  @override
  Widget build(BuildContext context) {
    return Selector<ThemeModeProvider, ThemeMode>(
      selector: (context, themeModeProv) => themeModeProv.themeMode,
      builder: (context, themeMode, child) => Column(
        // clipBehavior: Clip.none,
        children: [
          const AvatarRow(),
          const CreateStatistics(),
          Showcase.withWidget(
            key: guideKey,
            height: 160.h,
            width: 335.w,
            disableBarrierInteraction: true,
            container: NewGuideDialog(
              index: 1,
              onTop: () => {ShowCaseWidget.of(context).next()},
            ),
            child: const AdSpace(),
          )
          // FutureBuilder(
          //     future: Future.delayed(Duration(seconds: 1)),
          //     builder: (context, snapshot) {
          //       return snapshot.connectionState == ConnectionState.waiting
          //           ? Center(
          //               child: CircularProgressIndicator(),
          //             )
          //           : Expanded(
          //               child: SingleChildScrollView(
          //               child: Column(
          //                 children: [
          //                   Showcase.withWidget(
          //                     key: GuideKey,
          //                     height: 200.h,
          //                     width: 385.w,
          //                     container: GuideDialog(),
          //                     child: const CreateStatistics(),
          //                   )
          //                 ],
          //               ),
          //             ));
          //     })
          // ],
          // ),
          // ),
        ],
      ),
    );
  }
}

class AvatarRow extends StatelessWidget {
  const AvatarRow({super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 54.h), // left: 24.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(width: 24.w),
          const ProfileAvatar(),
          SizedBox(width: 10.w),
          SizedBox(
            //width: 280.w,
            child: const Column(
              crossAxisAlignment: CrossAxisAlignment.start, // Add this line
              mainAxisSize: MainAxisSize.min, // Add this line
              children: [UserName(), BadgeRow()],
            ),
          )
        ],
      ),
    );
  }
}

class ProfileAvatar extends StatelessWidget {
  const ProfileAvatar({super.key});

  @override
  Widget build(BuildContext context) {
    return Selector<UserProvider, String?>(
      selector: (context, userProv) => userProv.currentUser?.imageUrl,
      builder: (context, imageUrl, child) {
        return Container(
            height: 60,
            width: 60,
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              border: Border.all(width: 2, color: Colors.white),
              shape: BoxShape.circle,
              color: Colors.grey[700], // Background color for default avatar
            ),
            child: imageUrl != null
                ? CachedNetworkImage(
                    imageUrl: imageUrl,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => const Center(
                        child: CircularProgressIndicator(color: Colors.white)),
                    errorWidget: (context, url, error) => Image.asset(
                        'assets/imgs/img_default_avatar.jpg',
                        fit: BoxFit.cover),
                  )
                : SizedBox.shrink());
      },
    );
  }
}

class UserName extends StatelessWidget {
  const UserName({super.key});

  @override
  Widget build(BuildContext context) {
    return Selector2<ThemeModeProvider, UserProvider, (ThemeMode, String?)>(
        selector: (context, themeModeProv, userProv) =>
            (themeModeProv.themeMode, userProv.currentUser!.fullName),
        builder: (context, data, child) {
          final themeMode = data.$1;
          final fullName = data.$2;

          return Text(
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            fullName ?? '',
            textAlign: TextAlign.left,
            style: TextStyle(
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w700,
                fontSize: 20.sp,
                letterSpacing: 0,
                color:
                    themeMode == ThemeMode.dark ? Colors.white : Colors.black),
          );
        });
  }
}

class BadgeRow extends StatelessWidget {
  const BadgeRow({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(7),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min, // Let content determine width
        children: [
          const RankingLevel(),
          SizedBox(width: 6.w), // 14px left padding
          Image.asset('assets/imgs/img_badge1.png', width: 18.w, height: 18.h),
          SizedBox(width: 5.w),

          /// 14px between images
          Image.asset('assets/imgs/img_badge2.png', width: 17.w, height: 17.h),
          SizedBox(width: 5.w), // 14px between images
          Image.asset('assets/imgs/img_badge3.png',
              width: 16.5.w, height: 16.5.h),
        ],
      ),
    );
  }
}

class AdSpace extends StatelessWidget {
  const AdSpace({super.key});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(
            width: 375.w,
            height: 32.h,
            decoration: BoxDecoration(
              color: Color(0XFF181818),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 20.w),
          child: Row(
            children: [
              _storePlazaWidget(
                  text: 'My Store', imgUrl: 'assets/imgs/img_my_store.png'),
              SizedBox(width: 9.w),
              _storePlazaWidget(
                  text: 'Product Plaza',
                  imgUrl: 'assets/imgs/img_product_plaza.png')
            ],
          ),
        ),
      ],
    );
  }
}

class _storePlazaWidget extends StatelessWidget {
  final String text;
  final String imgUrl;

  const _storePlazaWidget(
      {super.key, required this.text, required this.imgUrl});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 162.w,
      height: 64.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(34, 34, 34, 1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Stack(
        children: [
          // Text that can overflow
          Padding(
            padding: EdgeInsets.only(
                left: 17.w, right: 66.w), // Right padding = image width
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                text,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w700,
                  fontSize: 16.sp,
                  fontFamily: 'Poppins',
                ),
                overflow: TextOverflow
                    .visible, // Allows text to flow outside container
                softWrap: false, // Prevents text wrapping
              ),
            ),
          ),
          // Image positioned on right
          Positioned(
            right: 0,
            child: Image.asset(
              imgUrl,
              width: 66.w,
              height: 64.h,
              fit: BoxFit.cover,
            ),
          ),
        ],
      ),
    );
  }
}

class RankingLevel extends StatelessWidget {
  const RankingLevel({super.key});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          width: 85.w,
          height: 18.h,
          margin: EdgeInsets.only(top: 2.h),
          padding: EdgeInsets.only(left: 14).r,
          decoration: BoxDecoration(
            color: Color(0XFFA8A4A1).withAlpha((255 * 0.3).floor()),
            borderRadius: BorderRadius.circular(9).r,
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                'Hustler',
                style: customTextStyle(opacity: .4),
              ),
              SizedBox(width: 5.w),
              SvgPicture.asset(
                'assets/icons/icon_arrow.svg',
                width: 3.5.w,
                height: 6.2.h,
              )
            ],
          ),
        ),
        Positioned(
          child: Container(
            width: 85 * 0.6,
            height: 18.h,
            margin: EdgeInsets.only(top: 2.h),
            decoration: BoxDecoration(
              color: Color(0XFFFF6F00).withAlpha((255 * 0.3).floor()),
              borderRadius: BorderRadius.circular(9).r,
            ),
          ),
        ),
        SvgPicture.asset(
          'assets/icons/icon_diamond.svg',
          width: 22.w,
          height: 22.h,
        ),
      ],
    );
  }
}
